package net.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author 王霄
 * @date 2021/8/27 23:13
 */
public class GroupChatClient {

    private static final String host = "127.0.0.1";
    private static final int port = 6666;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public void init() {
        try {
            this.selector = Selector.open();
            this.socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress(port));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            username = socketChannel.getLocalAddress().toString().substring(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void send(String msg) {
        try {
            socketChannel.write(ByteBuffer.wrap((username + " : " + msg).getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void read() {
        try {
            if (selector.select() > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    //监听读取事件
                    if (selectionKey.isReadable()) {
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        if (channel.read(buffer) > 0) {
                            String msg = new String(buffer.array());
                            System.out.println(msg);
                        }
                    }
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        GroupChatClient client = new GroupChatClient();
        client.init();
        new Thread(() -> {
            while (true) {
                client.read();
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            client.send(scanner.nextLine());
        }
    }
}
